package cn.FagDegrn.chatbot.api.application.job;


import cn.FagDegrn.chatbot.api.domain.ai.IOpenAI;
import cn.FagDegrn.chatbot.api.domain.zsxq.IzsxqApi;
import cn.FagDegrn.chatbot.api.domain.zsxq.model.aggregates.UnansweredAggregates;
import cn.FagDegrn.chatbot.api.domain.zsxq.model.vo.Topics;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Random;

@EnableScheduling
@Configuration
public class ChatbotSchedule {

    private Logger logger = LoggerFactory.getLogger(ChatbotSchedule.class);

    @Resource
    private IOpenAI openAI;
    @Resource
    private IzsxqApi zsxqApi;


    @Value("${chatai-api.groupId}")
    private String groupId;

    @Value("${chatai-api.cookie}")
    private String cookie;


    @Scheduled(cron = "0/30 * * * * ?")
    public void run(){
        logger.info("run方法开始执行");
        try{
            if (new Random().nextBoolean()){
                logger.info("随机休眠中");
                return;
            }

            GregorianCalendar calendar = new GregorianCalendar();
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            if(hour>24 || hour<7){
                logger.info("深夜时间不回答问题");
            }


            UnansweredAggregates unansweredAggregates = zsxqApi.queryUnansweredQuestionTopicId(groupId, cookie);
            List<Topics> topics = unansweredAggregates.getResp_data().getTopics();

            if (topics==null || topics.isEmpty()){
                logger.info("此次检索未查询到待回答的问题");
                return;
            }

            Topics topic = topics.get(0);
            String answer = openAI.doChatGPT(topic.getQuestion().getText().trim());
            boolean status = zsxqApi.answer(groupId, cookie, topic.getTopic_id(), answer, false);
            logger.info("编号：{}，问题：{}，回答：{}，状态：{}",topic.getTopic_id(),topic.getQuestion().getText(),answer,status);
        }catch (IOException e){
            logger.info("自动检索回答出现错误",e);
        }
    }
}
